package conf

import (
	"context"
	"time"

	"github.com/bwmarrin/snowflake"
	"github.com/gin-gonic/gin"
	"github.com/opentracing/opentracing-go"
)

// Span .
func Span(c *gin.Context, operationName string, record map[string]interface{}) context.Context {
	ctx := c.Request.Context()
	if parentSpan := opentracing.SpanFromContext(ctx); parentSpan != nil {
		span, newCTX := opentracing.StartSpanFromContext(ctx, operationName, opentracing.Tags(record), opentracing.StartTime(time.Now()))
		//parentSpan := opentracing.SpanFromContext(ctx)
		//span := conf.ZKTracer.StartSpan(operationName, opentracing.ChildOf(parentSpan.Context()), opentracing.Tags(record), opentracing.StartTime(time.Now()))
		defer span.Finish()
		c.Request = c.Request.WithContext(opentracing.ContextWithSpan(newCTX, span))
		ctx = c.Request.Context()
	}
	return ctx
}

// GenerateID GenerateID
func GenerateID() (id int64, err error) {
	node, err := snowflake.NewNode(1)
	if err != nil {
		return id, err
	}
	generateID := node.Generate()
	return int64(generateID), err
}
